$(function () {
	var grid;
	var fileSentIndex = 0;
	getAllProjects();

	function getAllProjects(){
		var datasource = [];

		var params = {
			'method' : 'GetAllProjects'
		};

		$.ajax({
			type: "POST",
			url: "/server/php/handler.php",
			//url: "/GARMOR/trunk/web/server/php/handler.php",
			dataType: "json",
			data: params,
			success: function(data, statusCode, jqXHRObj){
						grid = new Grid(data);
						grid.clear();
						var buttons = [];
						var columnNames= 
						[{label:"Proyecto", value:"projectName"},
                        {label:"Descripción",value:"projectDescription"},
                        {label:"Acciones", value:"Action"}];


			          	var editButton = 
			          		$('<button>')
			                .attr('id','edit')
                          	.attr('name','edit')
                          	.addClass('btn')
                          	.html('<i class="icon-edit"></i>Editar')
                          	.click(
                          	    function(evt){
                          	      var selectedObj = grid.dataSource[grid.selectedIndex];
                          	      openDialog(selectedObj);
                          	    }
                          	);

			           	var deleteButton = 
			           		$('<button>')
                            .attr('id','delete')
                            .attr('name','delete')
                            .addClass('btn btn-danger')
                            .html('<i class="icon-remove"></i>Remover')
                            .click(
                              function(){
                                var selectedObj = grid.dataSource[grid.selectedIndex];
                                $("#deleteDialog").modal();
                                $('#deleteMessage').text("Desea eliminar el proyecto: " + selectedObj.projectName);
                              }
                            );                        
			            buttons[buttons.length] = editButton;
			            buttons[buttons.length] = deleteButton;

			            grid.createGrid(columnNames, buttons);
					},
			error: function(error){
				console.log(error);
			},
			complete: function(){
				
			}
		});
	}

	function submitProject(){
		var params = {
			'projectId': projectId,
			'projectName' : $('#projectName').val(),
			'projectDescription' : $('#projectDescription').val(),
			'projectInsertedIds' : insertedIds.join(','),
			'datePickerBefore': $("#datePickerBefore").val(),
			'datePickerAfter': $("#datePickerAfter").val(),
			'sections': sections.join(','),
			'portraitId': portraitIndex,
			'method': 'SaveProject'
		};


		$.ajax({
			type: "POST",
			url: "/server/php/handler.php",
			//url: "/GARMOR/trunk/web/server/php/handler.php",
			data: params,
			success: function(data, statusCode, jqXHRObj){
				getAllProjects();
				$('#myModal').modal('hide');
			},
			error: function(error){
				console.log(error);
			},
			complete: function(){
				
			}
		});

		projectId = -1;
	}

	function deleteProject(){
		var params = {
			'method': 'DeleteProject',
			'projectId' : grid.dataSource[grid.selectedIndex].projectId
		}

		$.ajax({
			type: "POST",
			url: "/server/php/handler.php",
			//url: "/GARMOR/trunk/web/server/php/handler.php",
			data: params,
			success: function(data, statusCode, jqXHRObj){
				getAllProjects();
				$('#deleteDialog').modal('hide');
			},
			error: function(error){
				console.log(error);
			},
			complete: function(){
				
			}
		});
	}

	function openDialog(selectedObj){
		$('.submitdata').addClass('hidden');
		$('.updatedata').removeClass('hidden');

		$('#projectName').val(selectedObj.projectName);
        $('#projectDescription').val(selectedObj.projectDescription);
        $('#datePickerBefore').val(selectedObj.projectStart);
        $('#datePickerAfter').val(selectedObj.projectEnd);

        $("#myModal").modal({
			"backdrop" : "static",
			"keyboard" : true,
			"show" : true
		});
        
        var files = [];
        var checkedFileIndex = 0;

        projectId = selectedObj.projectId;

		for(var index in selectedObj.images){
			var image = selectedObj.images[index];
			var file = {};

			file.url = image.ImageURL;
			file.thumbnail_url = image.ThumbnailURL;
			file.id = image.ImageId;

			if(image.IsPortrait != 0){
				checkedFileIndex = index;
			}

			file.section = image.Section;

			files[files.length] = file;
		}

		$('.files').append(window.tmpl("template-upload")({'files' : files}));
		$('.files > tr > td > input[type="radio"]')[checkedFileIndex].checked = true;

		var selects = $('.files > tr > td > select');

		for(i = 0; i < selects.length; i++){
			selects[i].selectedIndex = files[i].section;
		}
    }

    function validateData(){
    	var pName = $('#projectName').val();
    	var pDesc = $('#projectDescription').val();
    	var dPickerB = $("#datePickerBefore").val();
    	var dPickerA = $("#datePickerAfter").val();

    	var errorMessage = null;

		if(pName == null || typeof pName == 'undefined' || pName.trim().length < 1){
			errorMessage = "Favor de ingresar el nombre del proyecto";
		}
		else if(pDesc == null || typeof pDesc == 'undefined' || pDesc.trim().length < 1){
			errorMessage = "Favor de ingresar la descripción del proyecto";
		}
		else if(dPickerB == null || typeof dPickerB == 'undefined' || dPickerB.trim().length < 1){
			errorMessage = "Favor de ingresar la fecha en la que empezó el proyecto";
		}
		else if($('.files > tr[class!=trheader]').length < 2){
			errorMessage = "Debe de haber cuando menos una imagen con la sección 'Antes' y otra con 'Después'";
		}

    	if(errorMessage != null){
    		$("#errorMessage").html(errorMessage);
    		$("#errorMessage").css('display', 'block');

    		return false;
    	}

    	return true;
    }

	var insertedIds = [];
	var sections = [];
	var projectId = -1;
    var portraitIndex = -1;
    var uploadingFiles = [];

    $('.fileupload').bind('fileuploadstop', function(data){
        fileSentIndex = 0;
        submitProject();
    });

    $('.fileupload').bind('fileuploaddone', function(e, data){
        insertedIds[insertedIds.length] = data.result.files[0].inserted_id;
    });

    $('.submitdata').click(function(){
    	if(validateData()){
	    	insertedIds = [];
	    	fileSentIndex = 0;
	        $('.start').click();
	    }
    });

    $('.updatedata').click(function(){
    	if(validateData()){
	    	insertedIds = [];
	    	fileSentIndex = 0;
	    	
	    	var hiddenInputs = $('.files > tr > td > input[type=hidden]');

	    	hiddenInputs.each(
	    		function(index, input){
	    			insertedIds[insertedIds.length] = input.value;
	    			sections[sections.length] = $('.files > tr > td > select')[index].selectedIndex;
	    		}
	    	);

	    	$('.files > tr > td > input[type=radio]').each(
	    		function(index, radio){
	    			if(radio.checked){
	    				portraitIndex = index;
	    			}
	    		}
	    	);

	    	if(typeof hiddenInputs != 'undefined' && hiddenInputs != null && hiddenInputs.length > 0){
	    		if(typeof hiddenInputs[portraitIndex] != 'undefined' && hiddenInputs[portraitIndex] != null){
		    		portraitIndex = hiddenInputs[portraitIndex].value;
				}
				else{
					portraitIndex = -1;
				}
		    }
		    else{
		    	portraitIndex = -1
		    }
	    	
	    	if(uploadingFiles != null && typeof uploadingFiles != 'undefined' && uploadingFiles.length > 0){
		    	$('.fileupload').fileupload('add', {files: uploadingFiles[0]});
		       	$('.start').click();
	       	}
	       	else{
	       		submitProject();
	       	}
        }
    });

    // Initialize the jQuery File Upload widget:
    $('.fileupload').fileupload({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        url: 'server/php/'
    });
	

	$('.fileupload').bind('fileuploadsubmit', 
		function (e, data) {
			var x = fileSentIndex;
			fileSentIndex = fileSentIndex + ($('tr.in').index()) - 1;
			if(typeof $('.files > tr > td > input[type=hidden]')[fileSentIndex] == 'undefined'){
				data.formData =	
				{
					isPrincipal : ($('input[type=radio]:checked').parent().parent().index()-1 == fileSentIndex),
					section : $(".files > tr > td > select")[fileSentIndex].selectedIndex
				}
			}

			fileSentIndex = x + 1;
		});

    $('#yes').click(deleteProject);

    $('#newproject').click(function(){
    	$('.updatedata').addClass('hidden');
		$('.submitdata').removeClass('hidden');
    });

    $("#myModal").on("hidden", function(){
    	projectId = -1;
    	insertedIds = [];
    	fileSentIndex = 0;
    	uploadingFiles = [];
    	sections = [];
    	portraitIndex = -1;

    	$('#projectName').val("");
        $('#projectDescription').val("");
        $('#datePickerBefore').val("");
        $('#datePickerAfter').val("");

        $('.fileupload')[0].reset();
		$(".files > tr[class!=trheader]").remove();

		$("#errorMessage").html("");
    	$("#errorMessage").css('display', 'none');
    });
    
	$('input[type=file]').change(function(e){
		$(e.currentTarget.files).each(
			function(index, file){
				uploadingFiles.push(file);
		});
	});
	
});